package cn.xfdzx.android.apps.shop.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;

import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.appbar.AppBarLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.adapter.OrderDetailGoodAdapter;
import cn.xfdzx.android.apps.shop.adapter.RefundReasonAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.OrderListBeen;
import cn.xfdzx.android.apps.shop.bean.PeiSongBeen;
import cn.xfdzx.android.apps.shop.bean.ReturnReasonBean;
import cn.xfdzx.android.apps.shop.contract.PeisongyuanContract;
import cn.xfdzx.android.apps.shop.evenbus.UpdateMyOrderMessage;
import cn.xfdzx.android.apps.shop.presenter.PeiSongPresenter;
import cn.xfdzx.android.apps.shop.util.DensityUtils;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ShopCarPopupWindow;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;


/**
 * 配送中的地图展示
 */
public class MapDistributionActivity extends BaseMvpActivity<PeiSongPresenter> implements PeisongyuanContract.View {


    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.abl_layout)
    AppBarLayout ablLayout;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_back_black)
    ImageView ivBackBlack;
    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.view_bg)
    View viewBg;
    @BindView(R.id.tv_songda_time)
    TextView tvSongdaTime;
    @BindView(R.id.tv_lianxi_peisong)
    TextView tvLianxiPeisong;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.rv_goods)
    RecyclerView rvGoods;
    @BindView(R.id.tv_more_pack_up)
    TextView tvMorePackUp;
    @BindView(R.id.tv_distribution_price)
    TextView tvTotalFreight;
    @BindView(R.id.tv_real_pay)
    TextView tvRealPay;
    @BindView(R.id.tv_time)
    TextView tvTime;//送达时间
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.tv_order_phone)
    TextView tvOrderPhone;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_order_note)
    TextView tvOrderNote;
    @BindView(R.id.tv_address_phone)
    TextView tvAddressPhone;
    @BindView(R.id.tv_peisong_type)
    TextView tvPeisongType;
    @BindView(R.id.tv_title_state)
    TextView tvTitleState;

    @BindView(R.id.tv_context)
    TextView tvContext;
    @BindView(R.id.tv_cancleorder)
    TextView tv_cancleorder;
    @BindView(R.id.tv_yi_preferential)
    TextView tvYiPreferential;//

    @BindView(R.id.map_ziti_view)
    MapView map;
    AMap aMap;//初始化地图控制器对象
    private LatLonPoint mStartPoint;//起点
    private LatLonPoint mEndPoint;//终点
     private LatLonPoint mQishouPoint;//骑手
    private OrderListBeen.DataBean dataBean;

    private float max_height;
    private float min_height;
    private boolean is_more_pack_up = false;//收起
    private Dialog dialog;
    private RelativeLayout.LayoutParams item_bar;
    private List<OrderListBeen.DataBean.CartInfoBean> list = new ArrayList<>();
    private OrderDetailGoodAdapter orderDetailGoodAdapter;
    private List<String> reasonDate;
    private RecyclerView recycleReason;
    private RefundReasonAdapter refundReasonAdapter;
    private TextView tv_why_submit;//提交
    private String selReason;
    private String applyType;//申请类型1取消2售后
    private String orderId;//
    private TextView tv_reasontitle;
    private String pageposition;
    private ShopCarPopupWindow cancel_order_PW;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        map.onCreate(savedInstanceState);

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_map_distribution;
    }

    @Override
    public void initView() {
        initHigh();
        dataBean = (OrderListBeen.DataBean) getIntent().getSerializableExtra("data");
        orderId = dataBean.getOrder_id();
        pageposition = getIntent().getStringExtra("pageposition");
        max_height = DensityUtils.dip2px(this, 510);
        min_height = DensityUtils.dip2px(this, 250);
        mPresenter = new PeiSongPresenter();
        mPresenter.attachView(this);

        addMarkerInScreenCenter();
        initData();
        ablLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
//AppBarLayout总的距离px
                int totalScrollRange = Math.abs(i);
                //当滑动的距离 <= toolbar高度的时候，改变Toolbar背景色的透明度，达到渐变的效果

                if (totalScrollRange <= max_height) {
                    float scale = (float) totalScrollRange / max_height;

                    if (totalScrollRange > 100) {
                        viewBg.setAlpha(scale);
                        rlTitle.setAlpha(scale);
                        llState.setAlpha(scale);
                    } else {
                        viewBg.setAlpha(0);
                        rlTitle.setAlpha(0);
                        ivBackBlack.setVisibility(View.VISIBLE);
                        llState.setAlpha(0);
                    }

                } else {
                    viewBg.setAlpha(1);
                    rlTitle.setAlpha(1);
                    ivBackBlack.setVisibility(View.GONE);
                    llState.setAlpha(1);

                }
            }
        });


        double totalPrice = 0;

        for (OrderListBeen.DataBean.CartInfoBean goodsBean : list) {
            totalPrice = Utils.addDouble(totalPrice, Utils.mul(Double.parseDouble(goodsBean.getMarketPrice()), goodsBean.getCart_num()));
        }
        double b = Utils.subDouble(Double.parseDouble(dataBean.getPay_price()), Double.parseDouble(dataBean.getTotal_postage()));

        totalPrice = Utils.subDouble(totalPrice, b);

        tvYiPreferential.setText("¥" + totalPrice);
        mPresenter.peiSong(dataBean.getOrder_id());
        runnable.run();



    }

    private void initData() {
        tvSongdaTime.setText(dataBean.getArrive_time());

        if (dataBean.getCartInfo().get(0).getStore() != null) {
            tvShopName.setText(dataBean.getCartInfo().get(0).getStore().getOffline_shop_name());
        }
        list.addAll(dataBean.getCartInfo());
        if (list.size() > 2) {
            tvMorePackUp.setVisibility(View.VISIBLE);
        } else {
            tvMorePackUp.setVisibility(View.GONE);
        }
        String shopId="";
        if (dataBean.getCartInfo().get(0).getStore() != null) {
            shopId=dataBean.getCartInfo().get(0).getStore().getId();
        }
        orderDetailGoodAdapter = new OrderDetailGoodAdapter(this, list,shopId);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvGoods.setLayoutManager(linearLayoutManager);
        rvGoods.setItemAnimator(new DefaultItemAnimator());
        rvGoods.setNestedScrollingEnabled(false);
        rvGoods.setAdapter(orderDetailGoodAdapter);
        tvTotalFreight.setText("¥" + dataBean.getTotal_postage());
        tvRealPay.setText("实付:¥" + dataBean.getPay_price());
        tvTime.setText(dataBean.getArrive_time());
        tvAddress.setText(dataBean.getUser_address().trim());

        tvAddressName.setText(dataBean.getReal_name());
        tvAddressPhone.setText(dataBean.getUser_phone() + "");
        if (dataBean.getDelivery_method() == 1) {
            tvPeisongType.setText("配送");
        } else if (dataBean.getDelivery_method() == 2) {
            tvPeisongType.setText("自提");
        }
        tvOrderPhone.setText(dataBean.getOrder_id() + "");
        tvOrderTime.setText(dataBean.get_pay_time() + "");
        tvOrderNote.setText(dataBean.getMark() + "");

        if (dataBean.getStatus() == 0) {
            tvTitleState.setText("商家已接单");
        } else if (dataBean.getStatus() == 1) {
            tvTitleState.setText("配送中");
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        map.onPause();

    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onPeiSongSuccess(PeiSongBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (bean.getData().getLat() == 0) {

            } else {
                if (!bean.getData().getMobile().isEmpty()){
                    tvLianxiPeisong.setVisibility(View.VISIBLE);
                }
                tvContext.setText("配送员：" + bean.getData().getName() + "      联系电话：" + bean.getData().getMobile());
                dialog = Utils.addDialog(this, R.layout.dialog,bean.getData().getMobile(), R.string.call, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isFastClick()){
                        dialog.dismiss();
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + bean.getData().getMobile());
                        intent.setData(data);
                        startActivity(intent);}
                    }
                });
                mQishouPoint=   new LatLonPoint(bean.getData().getLat(),bean.getData().getLng());
                aMap.addMarker(new MarkerOptions()
                        .position(new LatLng(mQishouPoint.getLatitude(), mQishouPoint.getLongitude()))
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_qishou)));

            }
        }

    }

    /**取消订单原因*/
    @Override
    public void getRefundRreasonSuccess(ReturnReasonBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            reasonDate = bean.getData();
            applyType = "1";
            if (null==cancel_order_PW){
                cancel_order_PW = new ShopCarPopupWindow(this, R.layout.pw_cancel_order_stock);
                cancel_order_PW.getRootView().findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        cancel_order_PW.shareClose();
                    }
                });

                cancel_order_PW.getRootView().findViewById(R.id.tv_why_submit).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (EmptyUtil.isNotEmpty(selReason)){
                            Map<String,Object> map = new HashMap<>();
                            map.put("orderId",orderId);
                            map.put("reason",selReason);
                            map.put("applyType",applyType);
                            mPresenter.getAfterServiceRequest(map);
                        }else {
                            Toast.makeText(MapDistributionActivity.this, "请选择原因", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        cancel_order_PW.shareClose();
                    }
                });
                tv_why_submit = cancel_order_PW.getRootView().findViewById(R.id.tv_why_submit);
                recycleReason = cancel_order_PW.getRootView().findViewById(R.id.lv_cancel_order_why);
                tv_reasontitle = cancel_order_PW.getRootView().findViewById(R.id.tv_reasontitle);
                tv_reasontitle.setText("取消订单原因");
                recycleReason.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
                refundReasonAdapter = new RefundReasonAdapter(reasonDate);
                recycleReason.setAdapter(refundReasonAdapter);
                refundReasonAdapter.setItemListener(new RefundReasonAdapter.OnItemOnClickListener() {
                    @Override
                    public void onItemClick(int position, String date) {
                        selReason = date;
                        refundReasonAdapter.setItemState(position);
                        tv_why_submit.setBackgroundResource(R.drawable.shape_02c557conner5);
                    }
                });
            }else {
                refundReasonAdapter.refreshDatas(reasonDate);
            }
//            if (EmptyUtil.isNotEmpty(selReason)){
//                tv_why_submit.setBackgroundResource(R.drawable.shape_02c557conner5);
//            }else {
//                tv_why_submit.setBackgroundResource(R.drawable.e3e3e3_3);
//            }

            cancel_order_PW.showPopupWindow();
        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getAfterServiceRequestSuccess(ReturnReasonBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Toast.makeText(this, "申请成功", Toast.LENGTH_SHORT).show();
            EventBus.getDefault().post(new UpdateMyOrderMessage(pageposition));

            finish();
        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        map.onSaveInstanceState(outState);
    }

    private void addMarkerInScreenCenter() {
        LatLng start = new LatLng(Double.parseDouble(dataBean.getCartInfo().get(0).getStore().getLat()), Double.parseDouble(dataBean.getCartInfo().get(0).getStore().getLng()));
        LatLng end = new LatLng(Double.parseDouble(dataBean.getAddress_lat()), Double.parseDouble(dataBean.getAddress_lng()));
        mStartPoint = new LatLonPoint(start.latitude, start.longitude);
        mEndPoint = new LatLonPoint(end.latitude, end.longitude);
        if (aMap == null) {
            aMap = map.getMap();
        }
        DPoint mPoint_start = new DPoint(start.latitude, start.longitude);
        DPoint mPoint_end = new DPoint(end.latitude, end.longitude);
        float distance = CoordinateConverter.calculateLineDistance(mPoint_start, mPoint_end);


        if (null != dataBean.getCartInfo()) {

            //设置地图的放缩级别
            if (distance < 100) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(end, 19));
            } else if (distance < 200) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(end, 18));
            } else if (distance < 500) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(end, 17));
            }else if (distance < 1000) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(end, 16));
            }else if (distance <2000) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(end, 15));
            }else if (distance < 5000) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(end, 14));
            }else if (distance < 10000) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(end, 13));
            }else if (distance < 20000) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(end, 12));
            }

            aMap.getUiSettings().setZoomControlsEnabled(false);
            aMap.getUiSettings().setZoomGesturesEnabled(false);
            aMap.getUiSettings().setScrollGesturesEnabled(false);
            aMap.setCustomMapStyle(
                    new com.amap.api.maps.model.CustomMapStyleOptions()
                            .setEnable(true)
                            .setStyleId("3b7df2aeffe4f90411241e09282a2cfa")//官网控制台-自定义样式 获取
            );
            setfromandtoMarker();
//            MarkerOptions markerOptions = new MarkerOptions();
//            markerOptions.position(latLng);
//            markerOptions.title(dataBean.getCartInfo().get(0).getStore().getOffline_shop_name());
//            markerOptions.snippet(dataBean.getCartInfo().get(0).getStore().getMobile());
//            markerOptions.visible(true);
//            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_shop_logo_ziti));
//            markerOptions.icon(bitmapDescriptor);
//            aMap.addMarker(markerOptions);

        }
    }

    /****
     * 起点终点图标设置
     */
    private void setfromandtoMarker() {

        RoundedCorners roundedCorners = new RoundedCorners(10);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
//        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(DensityUtils.dip2px(this, 54), DensityUtils.dip2px(this, 54));

        Glide.with(this)
                .load(dataBean.getStore().getLogo()).apply(options.transform(new CircleCrop(), roundedCorners)).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                Bitmap bitmap = drawableToBitmap(resource);
                BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
                aMap.addMarker(new MarkerOptions()
                        .position(new LatLng(mStartPoint.getLatitude(), mStartPoint.getLongitude()))
                        .icon(bitmapDescriptor));
            }
        });
        aMap.addMarker(new MarkerOptions().title("我的位置")
                .position(new LatLng(mEndPoint.getLatitude(), mEndPoint.getLongitude()))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_my_address)));

    }

    /**
     * Drawable转换成一个Bitmap
     *
     * @param drawable drawable对象
     * @return
     */
    public static final Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    @Override
    protected void onDestroy() {
        map.onDestroy();
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }


    private Dialog dialog_phone;
    @OnClick({R.id.tv_shop_name,R.id.iv_lianxi,R.id.tv_more_pack_up, R.id.tv_contact_shop, R.id.tv_lianxi_peisong, R.id.tv_fuzhi,R.id.iv_back,R.id.tv_cancleorder})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_shop_name:
                Intent intent = new Intent(this, ShopActivity.class);
                intent.putExtra("shop_id",dataBean.getStore().getId()+"");
                startActivity(intent);
                break;
            case R.id.iv_lianxi:
                if (Utils.isFastClick()) {
                    dialog_phone = Utils.addDialog(this, R.layout.dialog, "15810103429", R.string.call, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isFastClick()) {
                                dialog_phone.dismiss();
                                Intent intent = new Intent(Intent.ACTION_DIAL);
                                Uri data = Uri.parse("tel:" + "15810103429");
                                intent.setData(data);
                                startActivity(intent);
                            }
                        }
                    });
                    dialog_phone.show();
                }
                break;
            case R.id.tv_more_pack_up:
                if (Utils.isFastClick()) {
                    if (is_more_pack_up) {
                        orderDetailGoodAdapter.is_open = false;
                        orderDetailGoodAdapter.notifyDataSetChanged();
                        tvMorePackUp.setText(getResources().getText(R.string.an_more));
                        Drawable nav_up = getResources().getDrawable(R.drawable.icon_confirm_order_more);
                        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                        tvMorePackUp.setCompoundDrawables(null, null, nav_up, null);

                    } else {
                        orderDetailGoodAdapter.is_open = true;
                        orderDetailGoodAdapter.notifyDataSetChanged();
                        tvMorePackUp.setText(getResources().getText(R.string.pack_up));
                        Drawable nav_up = getResources().getDrawable(R.drawable.icon_location_on);
                        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());

                        tvMorePackUp.setCompoundDrawables(null, null, nav_up, null);

                    }
                    is_more_pack_up = !is_more_pack_up;
                }
                break;
            case R.id.tv_contact_shop:
            case R.id.tv_lianxi_peisong:
                if (null != dialog) {
                    dialog.show();
                }
                break;
            case R.id.tv_fuzhi:
                if (Utils.isFastClick()){
                Utils.copy(this, tvOrderPhone.getText().toString());
                Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show();}
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_cancleorder://取消订单
                if (Utils.isFastClick()){
                    mPresenter.getRefundRreason();
                }
                break;


        }
    }


    int startTime=0;
    int endTime=30;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            startTime++;
            if (startTime>=endTime) {
                startTime=0;
                mPresenter.peiSong(dataBean.getOrder_id());
            }
            handler.postDelayed(this, 1000);
        }
    };

}
